using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour
{
    public int maxHealth = 3;
    private int currentHealth;
    
    public Color hitColor = Color.red;
    public float hitFlashTime = 0.1f;
    
    private SpriteRenderer sprite;
    private Color originalColor;
    
    [Header("状态机相关")]
    [SerializeField] private EnemyStateMachine stateMachine;
    [SerializeField] private EnemyPatrolPoints patrolPoints;
    private Rigidbody2D rb;
    
    
    private void Awake()
    {
        sprite = GetComponent<SpriteRenderer>();
        originalColor = sprite.color;
        rb = GetComponent<Rigidbody2D>();
        
        // 自动添加或获取必要组件
        if (rb == null)
            rb = gameObject.AddComponent<Rigidbody2D>();
        
        if (patrolPoints == null)
            patrolPoints = GetComponent<EnemyPatrolPoints>();
        
        if (stateMachine == null)
            stateMachine = GetComponent<EnemyStateMachine>();
            
        // 配置Rigidbody2D属性
        if (rb != null)
        {
            rb.bodyType = RigidbodyType2D.Dynamic;
            rb.gravityScale = 0; // 2D游戏通常不需要重力
            rb.freezeRotation = true;
        }
    }
    
    // 初始化敌人(从对象池取出时调用)
    public void InitEnemy()
    {
        currentHealth = maxHealth;
        // 重置状态机到巡逻状态
        if (stateMachine != null)
        {
            stateMachine.SwitchState(stateMachine.patrolState);
        }
    }
    
    public void TakeDamage(int damage)
    {
        StartCoroutine(HitFlash());
        currentHealth -= damage;
        if (currentHealth <= 0)
        {
            Die();
        }
    }
    
    IEnumerator HitFlash()
    {
        sprite.color = hitColor;
        yield return new WaitForSeconds(hitFlashTime);
        sprite.color = originalColor;
    }
    
    private void Die()
    {
        // 死亡特效(可选)
        // GameObject deathEffect = Instantiate(deathEffectPrefab, transform.position, Quaternion.identity);
        // Destroy(deathEffect, 1f);
        
        // 回收到对象池
        EnemyPool.GetInstance().ReturnEnemy(gameObject);
    }
    
    /// <summary>
    /// 移动敌人
    /// </summary>
    /// <param name="direction">移动方向</param>
    /// <param name="speed">移动速度</param>
    public void Move(Vector2 direction, float speed)
    {
        if (rb != null && direction.sqrMagnitude > 0.1f)
        {
            rb.velocity = direction * speed;
        }
        else if (rb != null)
        {
            rb.velocity = Vector2.zero;
        }
    }
    
    // private void OnTriggerEnter2D(Collider2D other)
    // {
    //     if (other.CompareTag("PlayerBullet"))
    //     {
    //         TakeDamage(1);
    //         Destroy(other.gameObject);
    //     }
    // }
}
